<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>个人中心 - 宠物家政服务</title>
    <link rel="stylesheet" href="styles/main.css">
    <link rel="stylesheet" href="styles/profile.css">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        /* 消息提示样式 */
        .message {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 12px 20px;
            border-radius: 6px;
            color: white;
            font-weight: 500;
            z-index: 9999;
            display: flex;
            align-items: center;
            gap: 8px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            animation: slideIn 0.3s ease-out;
        }

        .message-success {
            background-color: #10b981;
        }

        .message-error {
            background-color: #ef4444;
        }

        .message-info {
            background-color: #3b82f6;
        }

        @keyframes slideIn {
            from {
                transform: translateX(100%);
                opacity: 0;
            }
            to {
                transform: translateX(0);
                opacity: 1;
            }
        }

        /* 空状态样式 */
        .empty-state {
            text-align: center;
            padding: 40px 20px;
            color: #6b7280;
        }

        .empty-state i {
            font-size: 48px;
            margin-bottom: 16px;
            opacity: 0.5;
        }

        .empty-state p {
            margin-bottom: 20px;
            font-size: 16px;
        }

        /* 导航栏用户头像样式 */
        .header .user-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            object-fit: cover;
        }
        /* 只显示当前激活的内容区 */
        .content-tab { display: none; }
        .content-tab.active { display: block; }
        
        /* 模态框样式 */
        .modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 10000;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .modal-content {
            background: white;
            border-radius: 12px;
            width: 90%;
            max-width: 500px;
            max-height: 90vh;
            overflow-y: auto;
            box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 20px 24px;
            border-bottom: 1px solid #e5e7eb;
        }

        .modal-header h3 {
            margin: 0;
            font-size: 18px;
            font-weight: 600;
            color: #111827;
        }

        .modal-close {
            background: none;
            border: none;
            font-size: 20px;
            color: #6b7280;
            cursor: pointer;
            padding: 4px;
            border-radius: 4px;
            transition: all 0.2s;
        }

        .modal-close:hover {
            background-color: #f3f4f6;
            color: #374151;
        }

        .modal-form {
            padding: 24px;
        }

        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 16px;
        }

        .photo-preview {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            margin-top: 8px;
        }

        .photo-preview img {
            width: 80px;
            height: 80px;
            object-fit: cover;
            border-radius: 8px;
            border: 2px solid #e5e7eb;
        }
    </style>
</head>
<body>
    <header class="header">
        <div class="container">
            <div class="logo">
                <i class="fas fa-paw"></i>
                <span>宠物家政</span>
            </div>
            <nav class="nav">
                <a href="index.html" class="nav-link">首页</a>
                <a href="services.html" class="nav-link">服务预约</a>
                <a href="orders.html" class="nav-link">我的订单</a>
                <a href="profile.html" class="nav-link active">个人中心</a>
            </nav>
            <div class="user-actions">
                <div class="user-info">
                    <img src="images/avatar-default.jpg" alt="用户头像" class="user-avatar">
                    <span class="user-name"></span>
                    <i class="fas fa-chevron-down"></i>
                </div>
            </div>
        </div>
    </header>

    <main class="main">
        <div class="container">
            <div class="profile-layout">
                <!-- 侧边栏 -->
                <aside class="profile-sidebar">
                    <div class="user-card">
                        <div class="user-avatar-large">
                            <img src="images/avatar-default.jpg" alt="用户头像" class="user-avatar">
                            <button class="avatar-edit">
                                <i class="fas fa-camera"></i>
                            </button>
                        </div>
                        <h3 class="user-name"></h3>
                        <p class="user-phone"></p>
                        <div class="user-stats">
                            <div class="stat-item">
                                <span class="stat-number">0</span>
                                <span class="stat-label">服务次数</span>
                            </div>
                            <div class="stat-item">
                                <span class="stat-number">0</span>
                                <span class="stat-label">宠物数量</span>
                            </div>
                        </div>
                    </div>

                    <nav class="profile-nav">
                        <a href="#profile" class="nav-item active" data-tab="profile">
                            <i class="fas fa-user"></i>
                            个人信息
                        </a>
                        <a href="#pets" class="nav-item" data-tab="pets">
                            <i class="fas fa-paw"></i>
                            宠物管理
                        </a>
                        <a href="#address" class="nav-item" data-tab="address">
                            <i class="fas fa-map-marker-alt"></i>
                            地址管理
                        </a>
                        <a href="#security" class="nav-item" data-tab="security">
                            <i class="fas fa-shield-alt"></i>
                            账户安全
                        </a>
                        <a href="#settings" class="nav-item" data-tab="settings">
                            <i class="fas fa-cog"></i>
                            系统设置
                        </a>
                    </nav>
                </aside>

                <!-- 主内容区 -->
                <div class="profile-content">
                    <!-- 个人信息 -->
                    <div id="profile" class="content-tab active">
                        <div class="tab-header">
                            <h2>个人信息</h2>
                            <p>管理您的个人资料和联系方式</p>
                        </div>

                        <form class="profile-form">
                            <div class="form-section">
                                <h3>基本信息</h3>
                                <div class="form-grid">
                                    <div class="form-group">
                                        <label for="real-name" class="form-label">真实姓名</label>
                                        <input type="text" id="real-name" class="form-input" value="" required>
                                    </div>
                                    <div class="form-group">
                                        <label for="nickname" class="form-label">昵称</label>
                                        <input type="text" id="nickname" class="form-input" value="">
                                    </div>
                                    <div class="form-group">
                                        <label for="gender" class="form-label">性别</label>
                                        <select id="gender" class="form-input">
                                            <option value="male">男</option>
                                            <option value="female">女</option>
                                            <option value="other">其他</option>
                                        </select>
                                    </div>
                                    <div class="form-group">
                                        <label for="birthday" class="form-label">生日</label>
                                        <input type="date" id="birthday" class="form-input" value="">
                                    </div>
                                </div>
                            </div>

                            <div class="form-section">
                                <h3>联系方式</h3>
                                <div class="form-grid">
                                    <div class="form-group">
                                        <label for="phone" class="form-label">手机号</label>
                                        <input type="tel" id="phone" class="form-input" value="" required>
                                    </div>
                                    <div class="form-group">
                                        <label for="email" class="form-label">邮箱</label>
                                        <input type="email" id="email" class="form-input" value="">
                                    </div>
                                </div>
                            </div>

                            <div class="form-section">
                                <h3>其他信息</h3>
                                <div class="form-group">
                                    <label for="bio" class="form-label">个人简介</label>
                                    <textarea id="bio" class="form-textarea" rows="4" placeholder="介绍一下自己..."></textarea>
                                </div>
                            </div>

                            <div class="form-actions">
                                <button type="submit" class="btn btn-primary">保存修改</button>
                                <button type="button" class="btn btn-outline">取消</button>
                            </div>
                        </form>
                    </div>

                    <!-- 宠物管理 -->
                    <div id="pets" class="content-tab">
                        <div class="tab-header">
                            <h2>宠物管理</h2>
                            <p>管理您的宠物信息和健康档案</p>
                            <button class="btn btn-primary" id="add-pet-btn">
                                <i class="fas fa-plus"></i>
                                添加宠物
                            </button>
                        </div>

                        <div class="pets-grid">
                            <!-- 宠物卡片由js动态渲染 -->
                            <div class="pet-card add-pet-card" onclick="showAddPetModal()">
                                <div class="add-pet-content">
                                    <i class="fas fa-plus"></i>
                                    <p>添加新宠物</p>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 地址管理 -->
                    <div id="address" class="content-tab">
                        <div class="tab-header">
                            <h2>地址管理</h2>
                            <p>管理您的常用服务地址</p>
                            <button class="btn btn-primary" onclick="showAddAddressModal()">
                                <i class="fas fa-plus"></i>
                                添加地址
                            </button>
                        </div>

                        <div class="address-list">
                            <!-- 地址卡片由js动态渲染 -->
                        </div>
                    </div>

                    <!-- 账户安全 -->
                    <div id="security" class="content-tab">
                        <div class="tab-header">
                            <h2>账户安全</h2>
                            <p>保护您的账户安全</p>
                        </div>

                        <div class="security-items">
                            <div class="security-item">
                                <div class="security-info">
                                    <i class="fas fa-lock"></i>
                                    <div>
                                        <h3>登录密码</h3>
                                        <p>定期更换密码可以保护账户安全</p>
                                    </div>
                                </div>
                                <button class="btn btn-outline">修改密码</button>
                            </div>

                            <div class="security-item">
                                <div class="security-info">
                                    <i class="fas fa-mobile-alt"></i>
                                    <div>
                                        <h3>手机绑定</h3>
                                        <p>已绑定：138****8888</p>
                                    </div>
                                </div>
                                <button class="btn btn-outline">更换手机</button>
                            </div>

                            <div class="security-item">
                                <div class="security-info">
                                    <i class="fas fa-shield-alt"></i>
                                    <div>
                                        <h3>两步验证</h3>
                                        <p>开启两步验证，提高账户安全性</p>
                                    </div>
                                </div>
                                <button class="btn btn-outline">开启验证</button>
                            </div>
                        </div>
                    </div>

                    <!-- 系统设置 -->
                    <div id="settings" class="content-tab">
                        <div class="tab-header">
                            <h2>系统设置</h2>
                            <p>个性化您的使用体验</p>
                        </div>

                        <div class="settings-items">
                            <div class="setting-item">
                                <div class="setting-info">
                                    <h3>消息通知</h3>
                                    <p>接收服务提醒和系统消息</p>
                                </div>
                                <label class="switch">
                                    <input type="checkbox" checked>
                                    <span class="slider"></span>
                                </label>
                            </div>

                            <div class="setting-item">
                                <div class="setting-info">
                                    <h3>推送通知</h3>
                                    <p>接收重要消息的推送通知</p>
                                </div>
                                <label class="switch">
                                    <input type="checkbox" checked>
                                    <span class="slider"></span>
                                </label>
                            </div>

                            <div class="setting-item">
                                <div class="setting-info">
                                    <h3>隐私保护</h3>
                                    <p>保护您的个人信息不被泄露</p>
                                </div>
                                <label class="switch">
                                    <input type="checkbox">
                                    <span class="slider"></span>
                                </label>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </main>

    <!-- 添加宠物模态框 -->
    <div id="addPetModal" class="modal" style="display: none;">
        <div class="modal-content">
            <div class="modal-header">
                <h3>添加宠物</h3>
                <button class="modal-close" onclick="closeAddPetModal()">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <form id="addPetForm" class="modal-form">
                <div class="form-group">
                    <label for="pet-name" class="form-label">宠物名称 *</label>
                    <input type="text" id="pet-name" name="name" class="form-input" required>
                </div>
                
                <div class="form-group">
                    <label for="pet-type" class="form-label">宠物类型 *</label>
                    <select id="pet-type" name="type" class="form-input" required>
                        <option value="">请选择宠物类型</option>
                        <option value="狗">狗</option>
                        <option value="猫">猫</option>
                        <option value="兔子">兔子</option>
                        <option value="仓鼠">仓鼠</option>
                        <option value="鸟">鸟</option>
                        <option value="鱼">鱼</option>
                        <option value="其他">其他</option>
                    </select>
                </div>
                
                <div class="form-group">
                    <label for="pet-breed" class="form-label">品种</label>
                    <input type="text" id="pet-breed" name="breed" class="form-input" placeholder="如：金毛、英短等">
                </div>
                
                <div class="form-row">
                    <div class="form-group">
                        <label for="pet-age" class="form-label">年龄 *</label>
                        <input type="number" id="pet-age" name="age" class="form-input" min="0" max="30" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="pet-gender" class="form-label">性别 *</label>
                        <select id="pet-gender" name="gender" class="form-input" required>
                            <option value="">请选择性别</option>
                            <option value="1">公</option>
                            <option value="2">母</option>
                            <option value="0">未知</option>
                        </select>
                    </div>
                </div>
                
                <div class="form-group">
                    <label for="pet-weight" class="form-label">体重 (kg)</label>
                    <input type="number" id="pet-weight" name="weight" class="form-input" min="0" step="0.1" placeholder="如：5.5">
                </div>
                
                <div class="form-group">
                    <label for="pet-photos" class="form-label">宠物照片</label>
                    <input type="file" id="pet-photos" name="photos" class="form-input" accept="image/*" multiple>
                    <div id="photo-preview" class="photo-preview"></div>
                </div>
                
                <div class="form-actions">
                    <button type="submit" class="btn btn-primary">添加宠物</button>
                    <button type="button" class="btn btn-outline" onclick="closeAddPetModal()">取消</button>
                </div>
            </form>
        </div>
    </div>

    <!-- 添加地址模态框 -->
    <div id="addAddressModal" class="modal" style="display: none;">
        <div class="modal-content">
            <div class="modal-header">
                <h3>添加地址</h3>
                <button class="modal-close" onclick="window.closeAddAddressModal()">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <form id="addAddressForm" class="modal-form">
                <div class="form-group">
                    <label for="receiverName" class="form-label">收货人姓名 *</label>
                    <input type="text" id="receiverName" name="receiverName" class="form-input" required>
                </div>
                <div class="form-group">
                    <label for="receiverPhone" class="form-label">收货人电话 *</label>
                    <input type="text" id="receiverPhone" name="receiverPhone" class="form-input" required>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label for="province" class="form-label">省份 *</label>
                        <input type="text" id="province" name="province" class="form-input" required>
                    </div>
                    <div class="form-group">
                        <label for="city" class="form-label">城市 *</label>
                        <input type="text" id="city" name="city" class="form-input" required>
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label for="district" class="form-label">区县 *</label>
                        <input type="text" id="district" name="district" class="form-input" required>
                    </div>
                    <div class="form-group">
                        <label for="detailAddress" class="form-label">详细地址 *</label>
                        <input type="text" id="detailAddress" name="detailAddress" class="form-input" required>
                    </div>
                </div>
                <div class="form-group">
                    <label for="isDefault" class="form-label">设为默认地址</label>
                    <input type="checkbox" id="isDefault" name="isDefault" value="1">
                </div>
                <div class="form-actions">
                    <button type="submit" class="btn btn-primary">添加地址</button>
                    <button type="button" class="btn btn-outline" onclick="window.closeAddAddressModal()">取消</button>
                </div>
            </form>
        </div>
    </div>

    <footer class="footer">
        <div class="container">
            <div class="footer-content">
                <div class="footer-section">
                    <h3>联系我们</h3>
                    <p><i class="fas fa-phone"></i> 400-123-4567</p>
                    <p><i class="fas fa-envelope"></i> service@petcare.com</p>
                </div>
                <div class="footer-section">
                    <h3>服务时间</h3>
                    <p>周一至周日 8:00-20:00</p>
                    <p>24小时在线客服</p>
                </div>
                <div class="footer-section">
                    <h3>关注我们</h3>
                    <div class="social-links">
                        <a href="#"><i class="fab fa-weixin"></i></a>
                        <a href="#"><i class="fab fa-weibo"></i></a>
                        <a href="#"><i class="fab fa-qq"></i></a>
                    </div>
                </div>
            </div>
            <div class="footer-bottom">
                <p>&copy; 2024 宠物家政服务. 保留所有权利.</p>
            </div>
        </div>
    </footer>

    <script src="https://cdn.jsdelivr.net/npm/axios@1.6.0/dist/axios.min.js"></script>
    <script src="js/api.js"></script>
    <script>
        // 个人中心页面JavaScript
        class ProfileManager {
            constructor() {
                this.currentUser = null;
                this.userPets = [];
                this.userAddresses = [];
                this.editingAddressId = null;
                this.init();
            }

            // 初始化
            async init() {
                try {
                    // 检查登录状态
                    if (!this.checkLoginStatus()) {
                        window.location.href = '/login.html';
                        return;
                    }

                    // 检查URL参数
                    this.checkUrlParams();

                    // 加载用户信息
                    await this.loadUserProfile();
                    
                    // 加载宠物信息
                    await this.loadUserPets();
                    
                    // 加载地址信息
                    await this.loadUserAddresses();
                    
                    // 绑定事件
                    this.bindEvents();
                    
                    // 初始化标签页切换
                    this.initTabSwitching();
                    
                } catch (error) {
                    console.error('初始化失败:', error);
                    this.showMessage('页面加载失败，请刷新重试', 'error');
                }
            }

            // 检查登录状态
            checkLoginStatus() {
                const token = localStorage.getItem('token');
                if (!token) {
                    return false;
                }
                return true;
            }

            // 检查URL参数
            checkUrlParams() {
                const urlParams = new URLSearchParams(window.location.search);
                const tab = urlParams.get('tab');
                if (tab === 'pets') {
                    // 延迟执行，确保DOM已经准备好
                    setTimeout(() => {
                        this.switchToPetsTab();
                        // 清除URL参数
                        window.history.replaceState({}, document.title, window.location.pathname);
                    }, 100);
                }
            }

            // 加载用户信息
            async loadUserProfile() {
                try {
                    const response = await petHouseAPI.user.getProfile();
                    this.currentUser = response.data;
                    this.updateUserInfo();
                } catch (error) {
                    console.error('获取用户信息失败:', error);
                    this.showMessage('获取用户信息失败', 'error');
                }
            }

            // 更新用户信息显示
            updateUserInfo() {
                if (!this.currentUser) return;

                // 更新头部用户信息
                const userNameElements = document.querySelectorAll('.user-name');
                const userAvatarElements = document.querySelectorAll('.user-avatar, .user-avatar-large img');
                const userPhoneElements = document.querySelectorAll('.user-phone');

                userNameElements.forEach(element => {
                    element.textContent = this.currentUser.realName || this.currentUser.username || '用户';
                });

                userAvatarElements.forEach(element => {
                    element.src = this.currentUser.avatarUrl || 'images/avatar-default.jpg';
                });

                userPhoneElements.forEach(element => {
                    element.textContent = this.currentUser.phone ? this.maskPhone(this.currentUser.phone) : '未设置';
                });

                // 更新个人信息表单
                this.updateProfileForm();
            }

            // 更新个人信息表单
            updateProfileForm() {
                if (!this.currentUser) return;

                const form = document.querySelector('.profile-form');
                if (!form) return;

                // 填充表单数据
                const realNameInput = form.querySelector('#real-name');
                const nicknameInput = form.querySelector('#nickname');
                const genderSelect = form.querySelector('#gender');
                const phoneInput = form.querySelector('#phone');
                const emailInput = form.querySelector('#email');
                const bioTextarea = form.querySelector('#bio');

                if (realNameInput) realNameInput.value = this.currentUser.realName || '';
                if (nicknameInput) nicknameInput.value = this.currentUser.username || '';
                if (genderSelect) {
                    genderSelect.value = this.currentUser.gender === 1 ? 'male' : 
                                        this.currentUser.gender === 0 ? 'female' : 'other';
                }
                if (phoneInput) phoneInput.value = this.currentUser.phone || '';
                if (emailInput) emailInput.value = this.currentUser.email || '';
                if (bioTextarea) bioTextarea.value = this.currentUser.info || '';
            }

            // 加载用户宠物信息
            async loadUserPets() {
                try {
                    console.log('开始加载宠物信息...');
                    const response = await petHouseAPI.pets.getAll();
                    this.userPets = response.data || [];
                    console.log('宠物信息加载成功:', this.userPets);
                    this.updatePetsDisplay();
                } catch (error) {
                    console.error('获取宠物信息失败:', error);
                    this.showMessage('获取宠物信息失败，请刷新页面重试', 'error');
                    // 宠物信息获取失败不影响主页面显示
                }
            }

            // 更新宠物显示
            updatePetsDisplay() {
                console.log('开始更新宠物显示...');
                console.log('当前宠物数据:', this.userPets);
                console.log('宠物数据长度:', this.userPets.length);
                
                const petsGrid = document.querySelector('.pets-grid');
                if (!petsGrid) {
                    console.error('找不到宠物网格容器 .pets-grid');
                    return;
                }
                
                console.log('找到宠物网格容器:', petsGrid);

                // 清空现有宠物卡片（保留添加宠物卡片）
                const existingPetCards = petsGrid.querySelectorAll('.pet-card:not(.add-pet-card)');
                console.log('清除现有宠物卡片数量:', existingPetCards.length);
                existingPetCards.forEach((card, index) => {
                    console.log(`移除宠物卡片 ${index + 1}:`, card);
                    card.remove();
                });

                // 检查添加宠物卡片是否存在
                const addPetCard = petsGrid.querySelector('.add-pet-card');
                console.log('添加宠物卡片是否存在:', !!addPetCard);

                // 添加宠物卡片
                console.log('开始添加宠物卡片，数量:', this.userPets.length);
                this.userPets.forEach((pet, index) => {
                    try {
                        console.log(`处理宠物 ${index + 1}:`, pet);
                        const petCard = this.createPetCard(pet);
                        
                        if (addPetCard) {
                            petsGrid.insertBefore(petCard, addPetCard);
                            console.log(`宠物卡片 ${index + 1} 插入到添加宠物卡片之前:`, pet.name);
                        } else {
                            petsGrid.appendChild(petCard);
                            console.log(`宠物卡片 ${index + 1} 添加到网格末尾:`, pet.name);
                        }
                        
                        // 验证卡片是否成功添加到DOM
                        const addedCard = petsGrid.querySelector(`.pet-card:not(.add-pet-card)`);
                        console.log(`验证宠物卡片 ${index + 1} 是否成功添加:`, !!addedCard);
                        
                    } catch (error) {
                        console.error(`创建宠物卡片 ${index + 1} 失败:`, error, pet);
                    }
                });

                // 最终验证
                const finalPetCards = petsGrid.querySelectorAll('.pet-card:not(.add-pet-card)');
                console.log('最终宠物卡片数量:', finalPetCards.length);
                finalPetCards.forEach((card, index) => {
                    console.log(`最终宠物卡片 ${index + 1}:`, card);
                });

                // 更新用户统计信息
                this.updateUserStats();
                console.log('宠物显示更新完成');
            }

            // 创建宠物卡片
            createPetCard(pet) {
                console.log('创建宠物卡片:', pet);
                
                const petCard = document.createElement('div');
                petCard.className = 'pet-card';
                
                let photoUrl = 'https://cheng-pethouse.oss-cn-wuhan-lr.aliyuncs.com/default.png';
                try {
                    if (pet.photoUrls && pet.photoUrls !== '[]' && pet.photoUrls !== 'null') {
                        const photoUrls = JSON.parse(pet.photoUrls);
                        if (Array.isArray(photoUrls) && photoUrls.length > 0) {
                            photoUrl = photoUrls[0];
                        }
                    }
                } catch (error) {
                    console.warn('解析宠物照片URL失败:', error, '使用默认图片');
                }
                
                petCard.innerHTML = `
                    <div class="pet-avatar">
                        <img src="${photoUrl}" alt="宠物照片" onerror="this.src='images/pet-default.jpg'">
                        <div class="pet-status online"></div>
                    </div>
                    <div class="pet-info">
                        <h3>${pet.name || '未命名'}</h3>
                        <p class="pet-breed">${pet.breed || '未知品种'}</p>
                        <p class="pet-age">${pet.age || 0}岁</p>
                        <div class="pet-tags">
                            <span class="tag">${pet.gender === 1 ? '公' : pet.gender === 2 ? '母' : '未知'}</span>
                            <span class="tag">${pet.weight ? pet.weight + 'kg' : '未知体重'}</span>
                        </div>
                    </div>
                    <div class="pet-actions">
                        <button class="btn btn-outline btn-sm" onclick="profileManager.editPet(${pet.id})">
                            <i class="fas fa-edit"></i>
                            编辑
                        </button>
                        <button class="btn btn-outline btn-sm" onclick="profileManager.viewPetHealth(${pet.id})">
                            <i class="fas fa-heartbeat"></i>
                            健康档案
                        </button>
                    </div>
                `;
                
                console.log('宠物卡片创建完成:', pet.name);
                return petCard;
            }

            // 加载用户地址信息
            async loadUserAddresses() {
                try {
                    const res = await petHouseAPI.address.getAll();
                    this.userAddresses = res.data;
                    this.updateAddressesDisplay();
                } catch (error) {
                    console.error('获取地址信息失败:', error);
                }
            }

            // 更新地址显示
            updateAddressesDisplay() {
                const addressList = document.querySelector('.address-list');
                if (!addressList) return;

                // 清空现有地址卡片
                addressList.innerHTML = '';

                if (this.userAddresses.length === 0) {
                    addressList.innerHTML = `
                        <div class="empty-state">
                            <i class="fas fa-map-marker-alt"></i>
                            <p>暂无地址信息</p>
                            <button class="btn btn-primary" onclick="profileManager.showAddAddressModal()">
                                添加地址
                            </button>
                        </div>
                    `;
                    return;
                }

                this.userAddresses.forEach(address => {
                    const addressCard = this.createAddressCard(address);
                    addressList.appendChild(addressCard);
                });
            }

            // 创建地址卡片
            createAddressCard(address) {
                const addressCard = document.createElement('div');
                addressCard.className = 'address-card';
                addressCard.innerHTML = `
                    <div class="address-info">
                        <div class="address-header">
                            <h3>${address.receiverName}</h3>
                            ${address.isDefault ? '<span class="address-tag default">默认</span>' : ''}
                        </div>
                        <p class="address-detail">${address.province}${address.city}${address.district}${address.detailAddress}</p>
                        <p class="address-contact">${address.receiverName} ${address.receiverPhone}</p>
                    </div>
                    <div class="address-actions">
                        ${!address.isDefault ? '<button class="btn btn-outline btn-sm" onclick="profileManager.setDefaultAddress(' + address.id + ')">设为默认</button>' : ''}
                        <button class="btn btn-outline btn-sm" onclick="profileManager.editAddress(${address.id})">编辑</button>
                        <button class="btn btn-outline btn-sm" onclick="profileManager.deleteAddress(${address.id})">删除</button>
                    </div>
                `;
                return addressCard;
            }

            // 更新用户统计信息
            updateUserStats() {
                const serviceCountElement = document.querySelector('.stat-number');
                const petCountElement = document.querySelectorAll('.stat-number')[1];
                
                if (serviceCountElement) {
                    serviceCountElement.textContent = '12'; // 这里需要从订单API获取实际数据
                }
                
                if (petCountElement) {
                    petCountElement.textContent = this.userPets.length;
                }
            }

            // 绑定事件
            bindEvents() {
                // 个人信息表单提交
                const profileForm = document.querySelector('.profile-form');
                if (profileForm) {
                    profileForm.addEventListener('submit', (e) => this.handleProfileSubmit(e));
                }

                // 头像上传
                const avatarEditBtn = document.querySelector('.avatar-edit');
                if (avatarEditBtn) {
                    avatarEditBtn.addEventListener('click', () => this.handleAvatarUpload());
                }

                // 添加宠物按钮
                const addPetBtn = document.getElementById('add-pet-btn');
                if (addPetBtn) {
                    addPetBtn.addEventListener('click', () => this.showAddPetModal());
                }

                // 添加地址按钮
                const addAddressBtn = document.querySelector('button[onclick="showAddAddressModal()"]');
                if (addAddressBtn) {
                    addAddressBtn.onclick = () => this.showAddAddressModal();
                }

                // 修改密码按钮
                const changePasswordBtn = document.querySelector('.security-item .btn');
                if (changePasswordBtn) {
                    changePasswordBtn.addEventListener('click', () => this.showChangePasswordModal());
                }

                // 添加宠物表单提交
                const addPetForm = document.getElementById('addPetForm');
                if (addPetForm) {
                    addPetForm.addEventListener('submit', (e) => this.handleAddPetSubmit(e));
                }

                // 宠物照片预览
                const petPhotosInput = document.getElementById('pet-photos');
                if (petPhotosInput) {
                    petPhotosInput.addEventListener('change', (e) => this.handlePetPhotosChange(e));
                }
            }

            // 处理个人信息提交
            async handleProfileSubmit(e) {
                e.preventDefault();
                
                const formData = new FormData(e.target);
                const profileData = {
                    realName: formData.get('real-name') || document.getElementById('real-name').value,
                    username: formData.get('nickname') || document.getElementById('nickname').value,
                    gender: document.getElementById('gender').value === 'male' ? 1 : 
                           document.getElementById('gender').value === 'female' ? 0 : -1,
                    phone: document.getElementById('phone').value,
                    email: document.getElementById('email').value,
                    info: document.getElementById('bio').value
                };

                try {
                    await petHouseAPI.user.updateProfile(profileData);
                    this.showMessage('个人信息更新成功', 'success');
                    await this.loadUserProfile(); // 重新加载用户信息
                } catch (error) {
                    console.error('更新个人信息失败:', error);
                    this.showMessage('更新失败，请重试', 'error');
                }
            }

            // 处理头像上传
            async handleAvatarUpload() {
                const input = document.createElement('input');
                input.type = 'file';
                input.accept = 'image/*';
                
                input.onchange = async (e) => {
                    const file = e.target.files[0];
                    if (!file) return;

                    try {
                        const response = await petHouseAPI.user.uploadAvatar(file);
                        this.showMessage('头像上传成功', 'success');
                        await this.loadUserProfile(); // 重新加载用户信息
                    } catch (error) {
                        console.error('头像上传失败:', error);
                        this.showMessage('头像上传失败，请重试', 'error');
                    }
                };

                input.click();
            }

            // 初始化标签页切换
            initTabSwitching() {
                const navItems = document.querySelectorAll('.profile-nav .nav-item');
                const contentTabs = document.querySelectorAll('.content-tab');

                navItems.forEach(item => {
                    item.addEventListener('click', (e) => {
                        e.preventDefault();
                        // 移除所有活动状态
                        navItems.forEach(nav => nav.classList.remove('active'));
                        contentTabs.forEach(tab => tab.classList.remove('active'));
                        // 添加活动状态
                        item.classList.add('active');
                        const targetTabId = item.getAttribute('data-tab');
                        contentTabs.forEach(tab => {
                            if(tab.id === targetTabId) {
                                tab.classList.add('active');
                            }
                        });
                    });
                });
            }

            // 显示添加宠物模态框
            showAddPetModal() {
                const modal = document.getElementById('addPetModal');
                if (modal) {
                    modal.style.display = 'flex';
                    // 重置表单
                    document.getElementById('addPetForm').reset();
                    document.getElementById('photo-preview').innerHTML = '';
                }
            }

            // 关闭添加宠物模态框
            closeAddPetModal() {
                const modal = document.getElementById('addPetModal');
                if (modal) {
                    modal.style.display = 'none';
                    // 重置表单
                    const form = document.getElementById('addPetForm');
                    if (form) {
                        form.reset();
                    }
                    // 清空照片预览
                    const photoPreview = document.getElementById('photo-preview');
                    if (photoPreview) {
                        photoPreview.innerHTML = '';
                    }
                }
            }

            // 处理添加宠物表单提交
            async handleAddPetSubmit(e) {
                e.preventDefault();
                
                // 获取提交按钮并设置加载状态
                const submitBtn = e.target.querySelector('button[type="submit"]');
                const originalText = submitBtn.textContent;
                submitBtn.disabled = true;
                submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 添加中...';
                
                try {
                    const formData = new FormData(e.target);
                    const petData = {
                        name: formData.get('name'),
                        type: formData.get('type'),
                        breed: formData.get('breed') || '',
                        age: parseInt(formData.get('age')),
                        gender: parseInt(formData.get('gender')),
                        weight: formData.get('weight') ? parseFloat(formData.get('weight')) : null,
                        photoUrls: '[]' // 暂时为空数组，后续可以扩展照片上传功能
                    };

                    // 添加宠物
                    const response = await petHouseAPI.pets.add(petData);
                    
                    // 显示成功消息
                    this.showMessage('宠物添加成功', 'success');
                    
                    // 关闭模态框
                    this.closeAddPetModal();
                    
                    // 重新加载宠物列表并确保切换到宠物管理标签
                    await this.refreshPetsAndSwitchTab();
                    
                } catch (error) {
                    console.error('添加宠物失败:', error);
                    this.showMessage('添加失败，请重试', 'error');
                } finally {
                    // 恢复按钮状态
                    submitBtn.disabled = false;
                    submitBtn.textContent = originalText;
                }
            }

            // 刷新宠物列表并切换到宠物管理标签
            async refreshPetsAndSwitchTab() {
                try {
                    // 确保切换到宠物管理标签
                    this.switchToPetsTab();
                    
                    // 重新加载宠物数据
                    await this.loadUserPets();
                    
                    // 添加一个小的延迟确保DOM更新完成
                    setTimeout(() => {
                        // 滚动到宠物列表顶部
                        const petsSection = document.getElementById('pets');
                        if (petsSection) {
                            petsSection.scrollIntoView({ behavior: 'smooth', block: 'start' });
                        }
                    }, 10000);
                    
                } catch (error) {
                    console.error('刷新宠物列表失败:', error);
                    this.showMessage('宠物列表刷新失败，请手动刷新页面', 'error');
                }
            }

            // 切换到宠物管理标签
            switchToPetsTab() {
                const petsNavItem = document.querySelector('.profile-nav .nav-item[data-tab="pets"]');
                const petsContentTab = document.getElementById('pets');
                
                if (petsNavItem && petsContentTab) {
                    // 移除所有活动状态
                    document.querySelectorAll('.profile-nav .nav-item').forEach(nav => nav.classList.remove('active'));
                    document.querySelectorAll('.content-tab').forEach(tab => tab.classList.remove('active'));
                    
                    // 添加活动状态
                    petsNavItem.classList.add('active');
                    petsContentTab.classList.add('active');
                }
            }

            // 编辑宠物
            editPet(petId) {
                // 这里可以实现编辑宠物的功能
                this.showMessage('编辑宠物功能开发中...', 'info');
            }

            // 查看宠物健康档案
            viewPetHealth(petId) {
                // 这里可以实现查看宠物健康档案的功能
                this.showMessage('健康档案功能开发中...', 'info');
            }

            // 显示添加地址模态框（支持编辑模式）
            showAddAddressModal(address = null) {
                const modal = document.getElementById('addAddressModal');
                if (modal) {
                    modal.style.display = 'flex';
                    const form = document.getElementById('addAddressForm');
                    form.reset();
                    if (address) {
                        form.receiverName.value = address.receiverName;
                        form.receiverPhone.value = address.receiverPhone;
                        form.province.value = address.province;
                        form.city.value = address.city;
                        form.district.value = address.district;
                        form.detailAddress.value = address.detailAddress;
                        form.isDefault.checked = address.isDefault === 1;
                    }
                }
            }

            // 关闭添加地址模态框时清除编辑状态
            closeAddAddressModal() {
                const modal = document.getElementById('addAddressModal');
                if (modal) {
                    modal.style.display = 'none';
                }
                this.editingAddressId = null;
            }

            // 处理添加/编辑地址表单提交
            async handleAddAddressSubmit(e) {
                e.preventDefault();
                const form = e.target;
                const formData = new FormData(form);
                const data = {
                    receiverName: formData.get('receiverName'),
                    receiverPhone: formData.get('receiverPhone'),
                    province: formData.get('province'),
                    city: formData.get('city'),
                    district: formData.get('district'),
                    detailAddress: formData.get('detailAddress'),
                    isDefault: formData.get('isDefault') ? 1 : 0
                };
                try {
                    if (this.editingAddressId) {
                        await petHouseAPI.address.update(this.editingAddressId, data);
                        this.showMessage('地址更新成功', 'success');
                        this.editingAddressId = null;
                    } else {
                        await petHouseAPI.address.add(data);
                        this.showMessage('地址添加成功', 'success');
                    }
                    this.closeAddAddressModal();
                    await this.loadUserAddresses();
                } catch (error) {
                    this.showMessage(this.editingAddressId ? '地址更新失败' : '地址添加失败', 'error');
                }
            }

            // 显示修改密码模态框
            showChangePasswordModal() {
                // 这里可以实现修改密码的模态框
                this.showMessage('修改密码功能开发中...', 'info');
            }

            // 手机号脱敏
            maskPhone(phone) {
                if (!phone || phone.length < 7) return phone;
                return phone.substring(0, 3) + '****' + phone.substring(7);
            }

            // 显示消息
            showMessage(message, type = 'info') {
                // 创建消息元素
                const messageDiv = document.createElement('div');
                messageDiv.className = `message message-${type}`;
                messageDiv.innerHTML = `
                    <i class="fas fa-${type === 'success' ? 'check-circle' : type === 'error' ? 'exclamation-circle' : 'info-circle'}"></i>
                    <span>${message}</span>
                `;

                // 添加到页面
                document.body.appendChild(messageDiv);

                // 自动移除
                setTimeout(() => {
                    messageDiv.remove();
                }, 3000);
            }

            // 处理宠物照片预览
            handlePetPhotosChange(e) {
                const files = e.target.files;
                const preview = document.getElementById('photo-preview');
                preview.innerHTML = '';

                for (let i = 0; i < files.length; i++) {
                    const file = files[i];
                    if (file.type.startsWith('image/')) {
                        const reader = new FileReader();
                        reader.onload = function(e) {
                            const img = document.createElement('img');
                            img.src = e.target.result;
                            preview.appendChild(img);
                        };
                        reader.readAsDataURL(file);
                    }
                }
            }

            // 调试方法 - 手动刷新宠物数据
            async debugRefreshPets() {
                console.log('=== 开始调试宠物数据刷新 ===');
                console.log('当前用户宠物数据:', this.userPets);
                console.log('当前用户宠物数量:', this.userPets.length);
                
                // 重新获取数据
                await this.loadUserPets();
                
                console.log('刷新后用户宠物数据:', this.userPets);
                console.log('刷新后用户宠物数量:', this.userPets.length);
                console.log('=== 调试完成 ===');
            }

            // 调试方法 - 检查DOM元素
            debugCheckDOM() {
                console.log('=== 开始调试DOM元素 ===');
                
                const petsGrid = document.querySelector('.pets-grid');
                console.log('宠物网格容器:', petsGrid);
                
                if (petsGrid) {
                    const allPetCards = petsGrid.querySelectorAll('.pet-card');
                    console.log('所有宠物卡片数量:', allPetCards.length);
                    
                    const petCards = petsGrid.querySelectorAll('.pet-card:not(.add-pet-card)');
                    console.log('非添加宠物卡片数量:', petCards.length);
                    
                    const addPetCard = petsGrid.querySelector('.add-pet-card');
                    console.log('添加宠物卡片:', addPetCard);
                    
                    petCards.forEach((card, index) => {
                        console.log(`宠物卡片 ${index + 1}:`, card);
                        const nameElement = card.querySelector('h3');
                        console.log(`宠物卡片 ${index + 1} 名称:`, nameElement ? nameElement.textContent : '未找到');
                    });
                }
                
                console.log('=== DOM调试完成 ===');
            }

            // 删除地址
            async deleteAddress(addressId) {
                if (!confirm('确定要删除该地址吗？')) return;
                try {
                    await petHouseAPI.address.delete(addressId);
                    this.showMessage('地址删除成功', 'success');
                    await this.loadUserAddresses();
                } catch (error) {
                    this.showMessage('地址删除失败', 'error');
                }
            }

            // 编辑地址
            editAddress(addressId) {
                const address = this.userAddresses.find(addr => addr.id === addressId);
                if (!address) return;
                this.editingAddressId = addressId;
                this.showAddAddressModal(address);
            }
        }

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', () => {
            window.profileManager = new ProfileManager();
            // 绑定添加地址表单事件
            const addAddressForm = document.getElementById('addAddressForm');
            if (addAddressForm) {
                addAddressForm.addEventListener('submit', function(e) {
                    window.profileManager.handleAddAddressSubmit(e);
                });
            }
            // 修复关闭弹窗全局方法
            window.closeAddAddressModal = function() {
                if (window.profileManager) {
                    window.profileManager.closeAddAddressModal();
                }
            };
        });

        // 全局函数，供HTML中的onclick调用
        function editPet(petId) {
            if (window.profileManager) {
                window.profileManager.editPet(petId);
            }
        }

        function viewPetHealth(petId) {
            if (window.profileManager) {
                window.profileManager.viewPetHealth(petId);
            }
        }

        function showAddPetModal() {
            if (window.profileManager) {
                window.profileManager.showAddPetModal();
            }
        }

        function showAddAddressModal() {
            if (window.profileManager) {
                window.profileManager.showAddAddressModal();
            }
        }

        function closeAddPetModal() {
            if (window.profileManager) {
                window.profileManager.closeAddPetModal();
            }
        }

        // 调试函数 - 在浏览器控制台中调用
        function debugPets() {
            if (window.profileManager) {
                console.log('=== 宠物数据调试 ===');
                console.log('用户宠物数据:', window.profileManager.userPets);
                console.log('宠物数量:', window.profileManager.userPets.length);
                window.profileManager.debugCheckDOM();
            } else {
                console.error('profileManager 未初始化');
            }
        }

        function refreshPets() {
            if (window.profileManager) {
                window.profileManager.debugRefreshPets();
            } else {
                console.error('profileManager 未初始化');
            }
        }

        function checkAPI() {
            console.log('=== API 调试 ===');
            console.log('petHouseAPI:', window.petHouseAPI);
            if (window.petHouseAPI && window.petHouseAPI.pets) {
                console.log('pets API 可用');
            } else {
                console.error('pets API 不可用');
            }
        }
    </script>
</body>
</html> 